/**
 * ----------------------------------------------------
 * 插件作用：实现 vue2 支持 vue3 Composition API，真香!!!
 * ----------------------------------------------------
 * see https://www.npmjs.com/package/@vue/composition-api
 * ----------------------------------------------------
 */

import type { App } from '@/plugins/types';
import VueCompositionAPI from '@vue/composition-api';

const chainingPlugin = {
  install(vue: App) {
    const optionalChaining = (obj: any, keyName: string) => {
      if (!obj) return undefined;
      let tmp = obj;
      const rest = keyName.split('.');
      for (const key in rest) {
        const name = rest[key];
        tmp = tmp?.[name];
      }
      return tmp || undefined;
    };
    // 添加为全局方法
    vue.prototype.$chaining = optionalChaining;
  }
};

export default (app: App) => {
  // 使vue2支持vue3 Composition API
  app.use(VueCompositionAPI);
  // 处理 vue2 template 链判断运算符（?.）
  app.use(chainingPlugin);
};
